# -*- coding: utf-8 -*-
import re
from django.template.defaultfilters import slugify as django_slugify
from miles.utils.encoding import ascii_translate


def slugify(value, instance=None, slug_field='slug', queryset=None, unique=True,
            force_ascii=True, overwrite_char_map=None, separator='-'):
    """ Based on: http://www.djangosnippets.org/snippets/369/ """
    # TODO: check field length
    if force_ascii:
        value = ascii_translate(value, overwrite_char_map)
    slug = django_slugify(value)
    separator = str(separator)
    if separator != '-':
        slug = slug.replace('-', separator)

    if instance and unique:
        if not queryset:
            queryset = instance.__class__._default_manager.all()
        if instance.pk:
            queryset = queryset.exclude(pk=instance.pk)
        orig_slug = slug
        count = 0
        is_unique = lambda s: queryset.filter(**{slug_field: slug}).count() == 0
        while not is_unique(slug):
            count += 1
            slug = ''.join([orig_slug, separator, str(count)])
    return slug


CAMEL_WORDS_PATTERN = re.compile('([A-Z][A-Z][a-z])|([a-z][A-Z])')

def splitcc(value, sep=' '):
    """
    Adds spaces (or other string if separator is given) between words in camel
    case strings. 
    
    Failure to space out string returns the original string.

    Split words:
    >>> splitcc('DMLSServicesOtherBSTextLLC')
    'DMLS Services Other BS Text LLC'

    Camel case to slug:
    >>> splitcc('DMLSServicesOtherBSTextLLC', separator='-').lower()
    'DMLS Services Other BS Text LLC'
    
    Based on: http://refactormycode.com/codes/896-string-args-to-lower-decorator#refactor_176070
    """
    if value is None:
        return None

    return CAMEL_WORDS_PATTERN.sub(lambda m: m.group()[:1] + sep + m.group()[1:], value)
